package com.mlethe.library.multi.api.listener;

import androidx.annotation.NonNull;

import com.mlethe.library.multi.api.MultiApi;
import com.mlethe.library.multi.api.MultiMedia;

import java.util.Map;

/**
 * @Author Mlethe
 * @Date 2023/3/15
 */
public final class OnActionCallback {

    /**
     * 用于防跨站点请求伪造
     */
    public String state;

    /**
     * 请求类型：1 授权登录，2 支付，3 分享
     */
    private final int mAction;

    /**
     * 是否获取用户信息
     */
    public boolean isGetUserInfo;

    /**
     * 回调监听
     */
    private OnActionListener mListener;

    /**
     * @param action   请求类型：1 授权登录，2 支付，3 分享
     * @param listener
     */
    public OnActionCallback(int action, OnActionListener listener) {
        this.mAction = action;
        this.mListener = listener;
    }

    /**
     * 获取请求类型：1 授权登录，2 支付，3 分享
     *
     * @return
     */
    public int getAction() {
        return mAction;
    }

    /**
     * 释放内存
     */
    private void release() {
        state = null;
        mListener = null;
    }

    public void onComplete(@NonNull MultiMedia media, @NonNull Map<String, String> map) {
        OnActionListener listener = mListener;
        release();
        if (listener == null) {
            return;
        }
        MultiApi.getInstance().post(() -> listener.onComplete(media, map));
    }

    public void onCancel(@NonNull MultiMedia media) {
        OnActionListener listener = mListener;
        release();
        if (listener == null) {
            return;
        }
        MultiApi.getInstance().post(() -> listener.onCancel(media));
    }

    public void onFailure(@NonNull MultiMedia media, int code, String msg) {
        OnActionListener listener = mListener;
        release();
        if (listener == null) {
            return;
        }
        MultiApi.getInstance().post(() -> listener.onFailure(media, code, msg));
    }
}
